<template>
    <div class="content">
        <BoxWithTitle class="left-wrapper" title="目录" icon="&#xe6f2;" isOther>
            <template #other>
               <el-button type="primary" size="mini" @click="handleAddReport" icon="el-icon-download" v-show="fileID != '' && !fielDErr">重新导入</el-button>
            </template>
            <div class="menu-tree">
                <el-button v-if="menuList.length == 0" type="primary" size="small" style="margin: 80px;" @click="handleAddMenu({node:{}},0,1)">新增目录</el-button>
                <treeMenu :treeData="menuList" name="lable" ref="treeMenu" nodeKey="id" expandALL isRightMenu
                @menuLeftClick="handleMenuClick"
                @addMenuItem="handleAddMenu" 
                @delMenuItem="handleDelTreeMenu" 
                @editMenuItem="handleAddMenu"
                 />
            </div>
        </BoxWithTitle>
        <div class="right-wrapper boxWrapper">
            <div class="office" v-show="this.fileID != '' && !fielDErr">
                <div id="editorDiv"></div>
            </div>  
            <div class="uploadFile" @click="handleAddReport" v-if="fileID == ''">
                <i class="el-icon-upload"></i>
                <p>在此处单击可选择相应报告模板导入</p>
            </div>

            <div class="uploadFile" @click="handleAddReport" v-if="fielDErr && this.fileID != ''">
                <i class="el-icon-upload"></i>
                <p>当前报告已丢失或无法加载，您可以重新导入</p>
            </div>
        </div>

        <el-dialog
       :visible.sync="uploadReportVisible"
        title="模板导入"
        width="400px"
        :before-close="handleCloseReportDialog"
        v-dialogDrag>
        <div class="modelTree">
            <treeMenu :treeData="modelTree" name="lable" ref="treeMenu" nodeKey="id" @menuLeftClick="handleModelMenuClick" />
        </div>
        <div class="dialog-footer">
            <el-button @click="handleCloseReportDialog" size="small" icon="el-icon-circle-close">取消</el-button>
            <el-button type="primary" @click="handleSaveReportDialog" size="small" icon="el-icon-upload">确定</el-button>
        </div>
    </el-dialog>


    <el-dialog
        title="目录管理"  v-dialogDrag :visible.sync="menuDialog" width="400px" :before-close="handleCloseMenuDialog">
        <el-form ref="menuForm" :model="menuForm" label-width="100px" size="medium">
            <el-form-item label="目录名称" required>
                <el-input v-model="menuForm.treeName" placeholder="请输入菜单名称"></el-input>
            </el-form-item>
            <el-form-item label="是否最底层"> 
            <el-switch v-model="menuForm.isBottom" active-color="#13ce66" inactive-color="#f0f0f0"  
                :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
            <el-form-item label="开始时间" v-show="!treeDataEdit"> 
            <el-date-picker
                v-model="menuForm.b_Time"
                type="date"
                format="yyyy年MM月dd日"
                value-format="yyyy-MM-dd"
                placeholder="开始时间">
            </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" v-show="!treeDataEdit"> 
            <el-date-picker
                v-model="menuForm.e_Time"
                type="date"
                format="yyyy年MM月dd日"
                value-format="yyyy-MM-dd"
                placeholder="开始时间">
            </el-date-picker>
            </el-form-item>
        <el-form-item>
            <el-button @click="handleCloseMenuDialog" size="small" icon="el-icon-circle-close">取消</el-button>
            <el-button type="primary" @click="handleSaveMenuDialog" size="small" icon="el-icon-circle-check">确定</el-button>
        </el-form-item>
        </el-form>  
    </el-dialog>
    </div>
</template>

<script>
import BoxWithTitle from '@/components/base/BoxWithTitle.vue'
import {reportTreeList,getOnlyOfficeEdit,getOnlyOfficeCopy,setReportFIleID,previewToJson,reportTreeDel,reportTreeEdit,reportTreeAdd} from "@/api/https";
import bus from '@/utils/eventBus.js';
import treeMenu from '@/components/base/treeMenu.vue'
import {baseUrl} from '@/api/baseUrl'
export default ({
    name:'report',
    components:{BoxWithTitle,treeMenu},
    data() {
        return{
            stationId:sessionStorage.getItem("stationId"),
            menuList:[],
            treeID:'',
            fileID:'',
            uploadReportVisible:false,
            modelTree:[],
            modelReportField:'',
            dates:{},
            configData:null,
            showRoleEdit:1,
            form:{
                token: null,
                onReady: null,
                onError: null,
                document: null,
                platform: null,
                documentType: null,
                editorConfig: null,
                onRequestClose: null,
                onOutdatedVersion: null,
                onDocumentStateChange: null,
                docEditor: null,
            },
            fielDErr:false,
            treeDataEdit:false,
            treeNodeLevel:'',
            menuForm:{},
            menuDialog:false
        }
    },
    mounted(){
        this.initBasin()
        this.handleGetMenuList(true)
    },
    activated(){
        this.initBasin()
        const newStationId = sessionStorage.getItem("stationId");
        if (this.stationId != newStationId) {
            this.stationId = newStationId;
            this.fileID = ''
            this.treeID = ''
            this.menuList = []
            this.handleGetMenuList(true)
        }else{
            
        }
    },
    deactivated(){
        bus.$off('station-changed', this.handleStationChanged);
    },
    beforeDestroy(){
        bus.$off('station-changed', this.handleStationChanged);
    },
    methods:{
        initBasin() {
            bus.$emit('showBasin', true);
            bus.$off('station-changed', this.handleStationChanged);
            bus.$on('station-changed', this.handleStationChanged);
        },
        handleStationChanged(newStationId, targetRoute) {
            if (!targetRoute || targetRoute === this.$route.name) {
                this.stationId = newStationId;
                this.fileID = ''
                this.treeID = ''
                this.menuList = []
                this.handleGetMenuList(true)
            }
        },
        handleGetMenuList(isReload) {
            reportTreeList({
                StationID:this.stationId,
                cateGroy:1
                }).then(res=>{  
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.menuList = res.data
                    if(isReload){
                        this.findLeafNodes(this.menuList);
                        this.$nextTick(()=>{
                            this.$refs.treeMenu.$refs.tree.setCurrentKey(this.treeID);
                            if(this.fileID){
                                this.handleEditReport()
                            }
                        })
                    }
                }else{
                    this.menuList = []
                }
            })
        },
        findLeafNodes(data) {
            if (data[0].children == null || data[0].children.length === 0){
                this.treeID = data[0].node.id
                this.fileID = data[0].node.fileID
                return
            }else{
                this.findLeafNodes(data[0].children);
            }
        },
        handleMenuClick(data){
            this.treeID = data.id
            this.fileID = data.fileID || ''
            this.fielDErr = true
            this.dates = {
                b_Time:data.b_Time || '',
                e_Time:data.e_Time || ''
            }
            if(this.showRoleEdit == 1){
                if(this.fileID != ''){
                    this.handleViewReport(0)
                }
            }else{
                this.$message.error('暂无权限，请联系管理员！')
            }
        },
        handleAddReport(){
            if(this.treeID == ''){
                this.$message.error('请选择目录！')
            }else{
                this.uploadReportVisible = true
                this.handleGetModelList()
            }
        },
        handleGetModelList() {
            reportTreeList({
                StationID:this.stationId,
                cateGroy:0
            }).then(res=>{  
                if(res.isSuccess){
                    this.modelTree = res.data || []
                }else{
                    this.modelTree = []
                }
            })
        },
        handleModelMenuClick(data){
            this.modelReportField = data.fileID || ''
        },
        handleCloseReportDialog(){
            this.modelReportField = ''
            this.uploadReportVisible = false
        },
        handleSaveReportDialog(){
            if(this.modelReportField != ''){
                getOnlyOfficeCopy(this.modelReportField).then(res=>{
                    if(res){
                        this.fileID = res.fileId || ''
                        setReportFIleID({
                            ID:this.treeID,
                            FileID:res.fileId
                        }).then(res1=>{
                            if(res1.isSuccess){
                                this.handleCloseReportDialog()
                                this.handleViewReport(1)
                            }
                        })
                    }else{
                        this.fileID = ''
                    }
                })
            }else{
                this.$message.error('此模板下没有报告！')
            }
        },
        handleViewReport(viewTp){
            if(this.fileID != ''){
                previewToJson(this.fileID,{
                    stationID:this.stationId,
                    b_Time:this.dates.b_Time || '',
                    e_Time:this.dates.e_Time || '',
                    viewTp:viewTp,
                    dataAddress:baseUrl.httpUrl
                }).then(res=>{
                    if(res){
                        this.fielDErr = false
                        this.configData = res
                        const obj = {
                            stationID:this.stationId,
                            b_Time:this.dates.b_Time,
                            e_Time:this.dates.e_Time,
                            ReprotID:this.treeID,
                            dataAddress:baseUrl.httpUrl
                        }
                        this.setEditor(this.configData,obj)
                    }
                })
            }
        },
        handleEditReport(){
            getOnlyOfficeEdit(this.fileID,{
                stationID:this.stationId,
                b_Time:'',
                e_Time:'',
                ReprotID:this.treeID,
                dataAddress:baseUrl.httpUrl
            }).then(res=>{
            if(res){
                this.configData = res
                const obj = {
                    stationID:res.stationID,
                    b_Time:res.b_Time,
                    e_Time:res.e_Time,
                    ReprotID:res.ReprotID,
                    dataAddress:baseUrl.httpUrl
                }
                this.setEditor(this.configData,obj)
            }
            })
        },
        setEditor(config,obj){
            const _this = this
            if (_this.form.docEditor) {
            _this.form.docEditor.destroyEditor();
            }
            config.editorConfig.plugins.pluginsData = [
            `${baseUrl.reportUrl}/sdkjs-plugins/tageditor/config.json`,
            `${baseUrl.reportUrl}/sdkjs-plugins/selecttable/config.json`,
            `${baseUrl.reportUrl}/sdkjs-plugins/echarteditor/config.json`,
            `${baseUrl.reportUrl}/sdkjs-plugins/svg/config.json`,
            ];
            const params = {
            ...config,
            events: {
                onInfo: function (data) {
                if (data && data.data && data.data.getConfig) {
                    _this.form.docEditor.serviceCommand("getConfig", obj);
                }
                },
            },
            };
            _this.form.docEditor = window.DocsAPI.DocEditor("editorDiv", params);
        },
        handleAddMenu(data,isEdit,treeNodeLevel){
            this.treeDataEdit = isEdit
            this.treeNodeLevel = treeNodeLevel || ''
            if(isEdit){
                const _editData = Object.assign({},data.node)
                this.menuForm = {..._editData}
            }else{
                this.menuForm = {
                    id: 0,
                    treeID:0,
                    stationID:this.stationId,
                    treeName:'',
                    upTreeID: treeNodeLevel == 1 ? data.node.upTreeID || 0 : data.node.treeID || 0,
                    isBottom:0,
                    reportUrl:'',
                    fileID:'',
                    b_Time:'',
                    e_Time:''
                }
            }
            this.menuDialog = true
        },
        handleDelTreeMenu(data){
            this.$confirm(`确认删除名称为 ${data.lable} 的节点？`,{
                type:'warning'
            }).then(confirm => {
                reportTreeDel({
                    id:data.node.id,
                    cateGroy:1
                }).then(res=>{  
                    if(res.isSuccess){
                        if(this.treeID == data.node.id){
                            this.fileID = ''
                            this.handleGetMenuList()
                        }
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }).catch(() => {});
        },
        handleSaveMenuDialog(){
            this.menuForm.cateGroy = 1
            if(!this.menuForm.treeName || this.menuForm.treeName == ''){
                this.$message.error('请输入菜单名称！')
                return false
            }
            if(this.treeDataEdit){
                reportTreeEdit(this.menuForm).then(res=>{  
                    if(res.isSuccess){
                        this.handleCloseMenuDialog()
                        this.handleGetMenuList(false)
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }else{
                reportTreeAdd(this.menuForm).then(res=>{  
                    if(res.isSuccess){
                        this.handleCloseMenuDialog()
                        this.handleGetMenuList(false)
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }
        },
        handleCloseMenuDialog(){
            this.menuDialog = false
            this.menuForm = {}
        },
    }
})
</script>
<style lang="scss" scoped>
.content{
    display: grid;
    grid-template-columns: 300px 1fr;
    height: calc(100vh - 120px);
    .left-wrapper{
       width: 300px;
        height: calc(100vh - 120px);
        flex-shrink: 0;
        .menu-tree{
            height: calc(100vh - 170px);
            overflow-y: auto;
        }
    }
    .right-wrapper{
        height: calc(100vh - 120px);
        overflow: auto;
        margin-left:10px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }
}
  .office{
    width: 100%;
    height: calc(100vh - 120px);
  }
  .uploadFile{
    width:360px;
    height: 180px;
    border:1px dashed #d9d9d9;
    border-radius: 6px;
    text-align: center;
    cursor: pointer;
    &:hover{
        border:1px dashed #409eff;
    }
    i{
        font-size: 67px;
        color: #c0c4cc;
        margin: 40px 0 16px;
        line-height: 50px;
    }
    p{
        color: #999;
        font-size: 14px;
        text-align: center;
    }
  }
  .modelTree{
    height: calc(100vh - 350px);
    overflow: auto;
  }
  .dialog-footer{
    display: flex;
    flex-direction: row;
    justify-content: end;
    margin-top:10px;
  }
</style>